<template>
  <view class="content">
    <image class="logo" src="/static/logo.png"></image>
    <view>
      <text class="title">{{ title }}</text>
    </view>
    <button class="authorize-btn" open-type="getUserInfo" @getuserinfo="handleWeixinAuthorize">微信授权</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      title: '富氢湿巾机',
      goback: false
    }
  },
  onLoad(opt) {
    this.goback = opt.goback === '1'
  },
  methods: {
    async handleWeixinAuthorize(e) {
      this.beginLoginLogic(e.detail)
    },
    async beginLoginLogic(data) {
      uni.showLoading({
        title: '授权中...'
      })

      let hasError = !(data && data.iv && data.encryptedData)
      if (!hasError) {
        // 1. 登录获取code
        let res = await uni.login({
          provider: 'weixin'
        })
        const code = res[1] && res[1].code
        hasError = !code
        if (!hasError) {
          // 2. 获取微信信息
          res = await uni.getUserInfo({
            provider: 'weixin',
            withCredentials: true
          })
          data = res[1]
          hasError = !data
          if (!hasError) {
            // 3. 解密微信信息
            res = await this.$utils.api.login.getWeiXinInfo(code, data.iv, data.encryptedData)
            hasError = !(res && res.head && res.head.ret === 0)
            if (!hasError) {
              // 4. 登录
              const wxInfo = res.data.wxInfo
              res = await this.$utils.api.login.getLogin(wxInfo, res.data.accessData)
              hasError = res.head.ret !== 0
              if (!hasError) {
                uni.setStorageSync(this.$consts.OPEN_ID, wxInfo.openId)
                uni.setStorageSync(this.$consts.USER_INFO, res.data)
                if (this.goback) {
                  uni.navigateBack({
                    delta: 1
                  })
                } else {
                  this.$utils.common.reLaunch(this.$consts.INDEX_PATH)
                }
              }
            }
          }
        }
      }
      if (hasError) {
        // 统一在这里提示 登录失败，不用写那么多的else分支
        this.$utils.common.toast.info('微信授权登录失败')
      }
      uni.hideLoading()
    }
  }
}
</script>

<style>
.content {
  text-align: center;
  height: 400upx;
}

.logo {
  height: 190rpx;
  width: 190rpx;
  margin-top: 147rpx;
}

.title {
  margin-top: 40rpx;
  font-size: 32rpx;
  color: #36363a;
}

.authorize-btn {
  position: fixed;
  bottom: 142rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 380rpx;
  height: 98rpx;
  border-radius: 8rpx;
  background: linear-gradient(90deg, #23c287, #82bf22);
  font-size: 16px;
  font-weight: 500;
  color: white;
  text-align: center;
  line-height: 98rpx;
  vertical-align: middle;
}
</style>
